<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { message } from "ant-design-vue";
  import { BasicModal, useModalInner, BasicForm, useForm } from '@gui-pkg/antdcomponents';
  import { formSchema } from './dept.data';
  import { addDeptStion, editDeptStion } from '@/api/system/dept';

  const isUpdate = ref(true);
  const emit = defineEmits(['success', 'register']);
  const deptId = ref('');

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      console.log(data.record, 'data.record');
      deptId.value = data.record.deptId;
      setFieldsValue({
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增部门' : '编辑部门'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      // TODO custom api
      console.log(values);
      // 向后台提交菜单数据
      if (unref(isUpdate)) {
        await editDeptStion({...values, deptId: unref(deptId)});
        message.success('编辑成功');
      } else {
        await addDeptStion(values);
        message.success('新增成功');
      }
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less" rel="stylesheet/less" scoped>

</style>
